<template>
  <div>
    <!--面包屑模块-->
    <el-breadcrumb separator-class="el-icon-arrow-right" style="padding: 10px">
      <el-breadcrumb-item :to="{ path: '/manage/' + this.id }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>学生管理</el-breadcrumb-item>
    </el-breadcrumb>
    <!--卡片视图区域-->
    <el-card>
      <!--搜索区域-->
      <el-col :span="24">
        <el-col :span="16">
          <el-input placeholder="请输入学生姓名查询" style="margin-bottom: 10px" v-model="queryInfo.query" clearable>
            <el-button slot="append" icon="el-icon-search" @click="getStudentList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="2">
          <el-button type="primary" style="margin-left: 15px" @click="addStudent">添加学生</el-button>
        </el-col>
        <el-col :span="2">
          <el-button type="primary" style="margin-left: 15px" @click="bachAddStudent">批量添加学生</el-button>
        </el-col>
        <el-col :span="2">
          <el-button type="success" style="margin-left: 15px" @click="importStudentExcel">一键导入表格</el-button>
        </el-col>
      </el-col>
      <!-- 表格显示区 -->
      <el-table :data="studentList" border style="width: 100%" ref="filterStudent" stripe>
        <el-table-column prop="studentID" label="学号" width="150"></el-table-column>
        <el-table-column prop="name" label="姓名" width="150"></el-table-column>
        <el-table-column prop="gender" label="性别" width="100"></el-table-column>
        <el-table-column prop="phone" label="联系方式" width="150"></el-table-column>
        <el-table-column prop="notes" label="备注" width="100"></el-table-column>
        <el-table-column prop="className" label="班级名称" width="200"></el-table-column>
        <el-table-column label="操作" width="200">
          <template slot-scope="scope">
            <el-tooltip effect="dark" content="修改信息" placement="top" :enterable="false">
              <el-button type="primary" size="mini" icon="el-icon-edit" @click="editStudent(scope.row.studentID)"></el-button>
            </el-tooltip>
            <el-tooltip effect="dark" content="删除信息" placement="top" :enterable="false">
              <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteStudent(scope.row.studentID)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页功能 -->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                     :current-page="queryInfo.pageNum" :page-sizes="[2, 3, 5, 10]" :page-size="queryInfo.pageSize"
                     layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </el-card>
    <!--   添加学生对话框   -->
    <el-dialog title="添加学生信息" :visible.sync="addStudentDialogVisible" width="50%" @close="addStudentDialogClosed">
      <el-form :model="addStudentForm" :rules="addStudentFormRules" label-width="100px" class="demo-ruleForm">
        <el-form-item label="学生学号" prop="studentID">
          <el-input v-model="addStudentForm.studentID" style="width: 30%"></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="addStudentForm.name" style="width: 30%"></el-input>
        </el-form-item>
        <el-form-item label="性别">
          <el-select v-model="addStudentForm.gender" placeholder="请选择学生性别">
            <el-option label="男" value="男"></el-option>
            <el-option label="女" value="女"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="联系方式" prop="phone">
          <el-input v-model="addStudentForm.phone" style="width: 30%"></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="notes">
          <el-input v-model="addStudentForm.notes" style="width: 30%"></el-input>
        </el-form-item>
        <el-form-item label="班级名称" prop="className">
          <el-select v-model="addStudentForm.className" placeholder="请选择班级名称">
            <el-option
              v-for="item in classNameList"
              :key="item"
              :value="item">
              {{ item }}
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
          <el-button @click="addStudentDialogClosed">取消</el-button>
          <el-button type="primary" @click="submitAddStudentForm">确定</el-button>
        </span>
    </el-dialog>
    <!--批量添加学生-->
    <el-dialog title="批量添加学生信息" :visible.sync="batchAddStudentDialogVisible" width="50%" @close="batchAddStudentDialogClosed">
      <el-form :model="batchAddStudentForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="上传文件">
          <el-upload
            class="upload-demo"
            :auto-upload="false"
            :file-list="fileList"
            :on-change="handleFileChange"
            :on-remove="handleRemove"
            :limit="1"
            accept=".xlsx,.xls"
          >
          <el-button size="small" type="primary">点击上传文件</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
      <el-button @click="batchAddStudentDialogClosed">取消</el-button>
      <el-button type="primary" @click="submitBatchAddStudentForm">确定</el-button>
    </span>
    </el-dialog>
    <!--   编辑学生信息对话框   -->
    <el-dialog title="修改学生信息" :visible.sync="editStudentDialogVisible" width="50%" @close="addStudentDialogClosed">
      <el-form :model="editStudentForm" :rules="addStudentFormRules" label-width="100px" class="demo-ruleForm">
        <el-form-item label="学生学号" prop="studentID">
          <el-input v-model="editStudentForm.studentID" style="width: 30%"></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="editStudentForm.name" style="width: 30%"></el-input>
        </el-form-item>
        <el-form-item label="性别">
          <el-select v-model="editStudentForm.gender" placeholder="请选择学生性别">
            <el-option label="男" value="男"></el-option>
            <el-option label="女" value="女"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="联系方式" prop="phone">
          <el-input v-model="editStudentForm.phone" style="width: 30%"></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="notes">
          <el-input v-model="editStudentForm.notes" style="width: 30%"></el-input>
        </el-form-item>
        <el-form-item label="班级名称" prop="className">
          <el-select v-model="editStudentForm.className" placeholder="请选择班级名称">
            <el-option
              v-for="item in classNameList"
              :key="item"
              :value="item">
              {{ item }}
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
          <el-button @click="editStudentDialogClosed">取消</el-button>
          <el-button type="primary" @click="submitEditStudentForm">确定</el-button>
        </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'ManageUserStudent',
  data () {
    return {
      id: '',
      queryInfo: {
        query: '',
        pageNum: 1,
        pageSize: 5
      },
      studentList: [],
      total: 0,
      // 添加学生表单
      addStudentForm: {
        studentID: '',
        name: '',
        gender: '',
        phone: '',
        notes: '',
        className: ''
      },
      classNameList: [],
      addStudentDialogVisible: false,
      addStudentFormRules: {
        studentID: [
          { required: true, message: '请输入11位学生学号', trigger: 'blur' },
          { pattern: /^[0-9]{11}$/, message: '学生学号必须是11位数字', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入正确形式的手机号', trigger: 'blur' },
          { pattern: /1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}/, message: '请输入正确形式的手机号', trigger: 'blur' }
        ]
      },
      batchAddStudentDialogVisible: false,
      batchAddStudentForm: {},
      // 编辑学生表单
      editStudentDialogVisible: false,
      editStudentForm: {
        studentID: '',
        name: '',
        gender: '',
        phone: '',
        notes: '',
        className: ''
      },
      fileList: [], // 上传的文件列表
      uploadedFile: null, // 上传成功的文件
      selectedFile: null
    }
  },
  created () {
    this.id = parseInt(this.$route.params.id)
    this.activePath = window.sessionStorage.getItem('activePath')
    this.getStudentList()
  },
  methods: {
    getStudentList () {
      this.$http.get('/student/showPage', {
        params: this.queryInfo
      }).then(({ data: res }) => {
        if (res.code === 200) {
          this.studentList = res.data
          this.total = res.total
        }
      })
    },
    // 页面选择
    handleSizeChange (newSize) {
      this.queryInfo.pageSize = newSize
      this.getStudentList()
    },
    handleCurrentChange (newPage) {
      this.queryInfo.pageNum = newPage
      this.getStudentList()
    },
    // 获取班级信息
    acquireClass () {
      this.$http.get('/class/acquireName').then(({ data: res }) => {
        if (res.code === 200) {
          this.classNameList = res.data
          console.log(res.data)
        }
      })
    },
    // 添加学生
    addStudent () {
      this.addStudentDialogVisible = true
      this.acquireClass()
    },
    // 重置表单信息
    restAddForm () {
      this.addStudentForm = {
        studentID: '',
        name: '',
        gender: '',
        phone: '',
        notes: '',
        className: ''
      }
    },
    // 提交添加学生信息
    submitAddStudentForm () {
      this.$http.post('/student/insert', this.addStudentForm).then(({ data: res }) => {
        if (res.code === 200) {
          this.$message.success('添加学生成功')
          this.addStudentDialogVisible = false
          this.restAddForm()
          this.getStudentList()
        }
      })
    },
    addStudentDialogClosed () {
      this.addStudentDialogVisible = false
      this.restAddForm()
    },
    // 批量添加学生
    bachAddStudent () {
      this.batchAddStudentDialogVisible = true
    },
    // 一键导入学生表格
    importStudentExcel() {
      // 创建一个隐藏的文件输入框
      const input = document.createElement('input')
      input.type = 'file'
      input.accept = '.xlsx,.xls'
      input.style.display = 'none'
      
      // 监听文件选择事件
      input.addEventListener('change', (event) => {
        const file = event.target.files[0]
        if (!file) return
        
        // 检查文件类型
        const allowedTypes = ['application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet']
        const fileExtension = file.name.split('.').pop().toLowerCase()
        if (!allowedTypes.includes(file.type) && !['xls', 'xlsx'].includes(fileExtension)) {
          this.$message.error('文件格式不正确，请上传 .xlsx 或 .xls 格式的文件')
          return
        }
        
        // 创建 FormData 对象并提交
        const formData = new FormData()
        formData.append('file', file)
        
        // 显示加载提示
        const loading = this.$loading({
          lock: true,
          text: '正在导入学生数据...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        
        // 发送请求
        this.$http.post('/studentFile/upload', formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        }).then(({ data: res }) => {
          loading.close()
          if (res.code === 200) {
            this.$message.success(`学生数据导入成功！`)
            this.getStudentList() // 刷新学生列表
          } else {
            this.$message.error(res.message || '导入失败')
          }
        }).catch(error => {
          loading.close()
          console.error('导入学生数据出错:', error)
          this.$message.error('导入学生数据出错: ' + error.message)
        })
      })
      
      // 触发文件选择对话框
      document.body.appendChild(input)
      input.click()
      
      // 在选择文件后移除输入元素
      input.addEventListener('input', () => {
        document.body.removeChild(input)
      })
    },
    // 当用户选择文件时触发
    handleFileChange (file, fileList) {
      // 检查文件类型
      const allowedTypes = ['application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet']
      const fileExtension = file.name.split('.').pop().toLowerCase()
      if (!allowedTypes.includes(file.raw.type) && !['xls', 'xlsx'].includes(fileExtension)) {
        this.$message.error('文件格式不正确，请上传 .xlsx 或 .xls 格式的文件')
        this.fileList = [] // 清空文件列表
        return
      }

      if (file.raw) {
        this.selectedFile = file.raw // 保存选中的文件
      }
      this.fileList = fileList // 更新文件列表
    },
    // 当用户移除文件时触发
    handleRemove (file, fileList) {
      this.selectedFile = null // 清空选中的文件
      this.fileList = fileList // 更新文件列表
    },
    // 关闭对话框时的回调
    batchAddStudentDialogClosed () {
      this.batchAddStudentDialogVisible = false
    },
    // 提交批量添加学生表单
    submitBatchAddStudentForm () {
      // 检查文件是否选择
      if (!this.selectedFile) {
        this.$message.error('请上传文件')
        return
      }
      // 创建 FormData 对象
      const formData = new FormData()
      formData.append('file', this.selectedFile)
      this.$http.post('/studentFile/upload', formData, {
        headers: {
          'Content-Type': 'multipart/form-data' // 必须使用 multipart/form-data
        }
      }).then(({ data: res }) => {
        if (res.code === 200) {
          this.$message.success('批量添加成功')
          this.batchAddStudentDialogVisible = false
        }
      })
    },
    // 编辑学生信息
    editStudent (studentID) {
      this.$http.get('/student/query', {
        params: { studentID: studentID }
      }).then(({ data: res }) => {
        if (res.code === 200) {
          this.acquireClass()
          this.editStudentForm = res.data
          this.editStudentDialogVisible = true
          this.selectedFile = null
          this.getStudentList()
        }
      })
    },
    // 重置表单
    restEditForm () {
      this.editStudentForm = {
        studentID: '',
        name: '',
        gender: '',
        phone: '',
        notes: '',
        className: ''
      }
    },
    submitEditStudentForm () {
      this.$http.put('/student/update', this.editStudentForm).then(({ data: res }) => {
        if (res.code === 200) {
          this.$message.success('更新学生信息成功')
          this.editStudentDialogVisible = false
          this.restEditForm()
          this.getStudentList()
        }
      })
    },
    editStudentDialogClosed () {
      this.editStudentDialogVisible = false
      this.restEditForm()
    },
    // 删除学生
    async deleteStudent (studentID) {
      const res = await this.$confirm('此操作将永久删除该学生, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // 用户取消删除就返回res
      if (res !== 'confirm') {
        this.$message.info('取消删除')
      } else {
        this.$http.delete('/student/' + studentID).then(({ data: result }) => {
          if (result.code !== 200) {
            this.$message.error('删除学生失败')
          } else {
            this.$message.success('删除学生成功')
            this.getStudentList()
            // 刷新页面
            window.location.reload() // 完全刷新页面
          }
        })
      }
    }
  }
}
</script>

<style scoped lang="less">

</style>
